/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tardistv.controller;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import tardistv.model.Episode;
import tardistv.model.Show;
import tardistv.utilities.Network;

/**
 *
 * @author alejandro
 */
public class TvCountDown {

    public TvCountDown() {
    }

    public void getEpisodesOf(Show show) {
        try {
            String code = Network.HTMLSource("http://tvcountdown.com/" + show.getCode());
            code = code.split("<table class=\"episode_list_table\" summary=\"List of episodes, ordered chronologically. Table is without headings: First column contains the series name, second the episode number, third the episode name, fourth tells how long until it airs, fifth tells the air date.\" style=\"width:848px;margin-top:6px\">")[1].split("</table>")[0];
            String[] chunks = code.split("<tr class=\"");
            for (int i = 1; i < chunks.length; i++) {
                Episode episode = new Episode();
                String[] lines = chunks[i].split("\n");
                episode.setAired(lines[0].contains("bc_p"));
                episode.setNumber(lines[2].split(">")[1].split("<")[0]);
                episode.setName(lines[4].split(">")[1].split("<")[0]);
                show.addEpisode(episode);
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(TvCountDown.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TvCountDown.class.getName()).log(Level.SEVERE, null, ex);
        }
        Controller.getInstance().showFilledWithEpisodes(show);
    }

    public ArrayList<Show> getShows() {
        ArrayList<Show> shows = new ArrayList<Show>();
        try {
            String code = (Network.HTMLSource("http://tvcountdown.com/?series_status_listing"));
            code = code.split("<table class=\"episode_list_table\" style=\"width:845px\">")[1].split("</table>")[0];
            String[] chunks = code.split("<tr>");
            for (int i = 1; i < chunks.length; i++) {
                String data = chunks[i].split("<a href=\"")[1].split("<")[0];
                Show show = new Show();
                show.setCode(data.split("\"")[0]);
                show.setName(data.split(">")[1]);
                shows.add(show);
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(TvCountDown.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TvCountDown.class.getName()).log(Level.SEVERE, null, ex);
        }
        return shows;
    }
}
